package com.meng.listview_scrolldelete;

import android.animation.ValueAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

/**
 * Created by Administrator on 2017/5/19.
 */

public class ItemLayout extends LinearLayout{
    private Scroller scroller;
    private int menuWidth;
    private static final int duration = 300;
    public ItemLayout(Context context) {
        super(context);
        init();
    }
    public ItemLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    private void init() {
        scroller = new Scroller(getContext());

    }

    public int getMenuWidth() {
        return menuWidth;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        View menuView = getChildAt(1);
        if(menuView == null){
            throw new RuntimeException("布局配置不正确");
        }
        menuView.measure(0,0);
        menuWidth = menuView.getMeasuredWidth();
    }

    /**
     * 关闭菜单
     */
    public void closeMenu(){
        smoothScrollTo(0,0);
    }

    /**
     * 打开菜单
     */
    public void showMenu(){
        smoothScrollTo(menuWidth,0);
    }

    /**
     * 平滑的滚动
     * @param scrollX
     * @param scrollY
     */
    private void smoothScrollTo(int scrollX,int scrollY){
        int startX = getScrollX();
        int startY = getScrollY();
        int dx = scrollX - startX;
        int dy = scrollY - startY;
        scroller.startScroll(startX,startY,dx,dy,duration);
        invalidate();
    }

    @Override
    public void computeScroll() {
        super.computeScroll();
        if(!scroller.isFinished()){
            if(scroller.computeScrollOffset()){
                scrollTo(scroller.getCurrX(),0);
                invalidate();
            }
        }
    }

    public boolean isShowMenu(){
        return getScrollX() != 0;
    }
    public boolean isMenuOpened(){
        return getScrollX() == menuWidth;
    }
    public boolean shouleOpenMenu(){
        return getScrollX() >= getMenuWidth()/3;
    }

    public void startDeleteAnim() {
        if(valueAnimator == null){
            valueAnimator = ValueAnimator.ofInt(0,-getHeight());
            valueAnimator.setDuration(500);
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                   int value = (int) animation.getAnimatedValue();
                    setPadding(getPaddingLeft(),value,getPaddingRight(),getPaddingBottom());
                }
            });
        }
        valueAnimator.start();
    }
    private ValueAnimator valueAnimator;
}
